import {
  AlipayCircleOutlined,
  LockOutlined,
  MobileOutlined, SyncOutlined,
  TaobaoCircleOutlined,
  UserOutlined, WechatOutlined, WeiboCircleOutlined
} from '@ant-design/icons';
import {Alert, Button, message, Modal, Tabs} from 'antd';
import React, {useState} from 'react';
import {ProFormCaptcha, ProFormText, LoginForm} from '@ant-design/pro-form';
import {useIntl, history, FormattedMessage, useModel, SelectLang} from 'umi';
import Footer from '@/components/Footer';
import {login, scanLogin, scanResult} from '@/services/ant-design-pro/api';
import {getFakeCaptcha} from '@/services/ant-design-pro/login';

import styles from './index.less';

const LoginMessage: React.FC<{
  content: string;
}> = ({content}) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);

const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
  const [type, setType] = useState<string>('account');
  const {initialState, setInitialState} = useModel('@@initialState');

  const intl = useIntl();

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      await setInitialState((s: any) => ({
        ...s,
        currentUser: userInfo,
      }));
    }
  };

  const handleSubmit = async (values: API.LoginParams) => {
    try {
      // 登录
      const msg = (await login({...values, type})) as API.Result<string>;
      console.log(msg.data);
      if (msg.status === 'ok') {
        const defaultLoginSuccessMessage = intl.formatMessage({
          id: 'pages.login.success',
          defaultMessage: '登录成功！',
        });
        message.success(defaultLoginSuccessMessage);
        let token = msg?.data;
        if (token) {
          localStorage.setItem('token', token);
        }
        await fetchUserInfo();
        /** 此方法会跳转到 redirect 参数所在的位置 */
        if (!history) return;
        const {query} = history.location;
        const {redirect} = query as { redirect: string };
        history.replace(redirect || '/');
        return;
      }
    } catch (error) {
      let e = error as Error;
      // const defaultLoginFailureMessage = intl.formatMessage({
      //   id: 'pages.login.failure',
      //   defaultMessage: '登录失败，请重试！',
      // });
      // message.error(defaultLoginFailureMessage);
      // 如果失败去设置用户错误信息
      console.log(e.message);
      setUserLoginState({
        status: 'error',
        type: type,
        currentAuthority: 'guest',
        msg: e.message,
      });
      console.log(userLoginState);
    }
  };
  const {status, msg, type: loginType} = userLoginState;
  const [showScanLogin, setShowScanLogin] = useState<boolean>(false);
  const [scanQrCode, setScanQrCode] = useState<String>();
  const [scanKey, setScanKey] = useState<String>();

  const [count, setCount]: [number, any] = useState(0);
  let interval: number | undefined;
  const loadScanData = async () => {
    let data = await scanLogin();
    console.log(data);
    setScanQrCode(data.url);

    let sk = data.key;
    let cs = data.expire;
    // cs = 10;
    setCount(cs);
    setScanKey(data.key);
    setShowScanLogin(true);

    if (interval) {
      clearInterval(interval);
    }

    interval = window.setInterval(async () => {
      cs -= 1;
      setCount(cs);

      if (cs <= 0) {
        clearInterval(interval);
      }
      let data = await scanResult(sk);
      // let data = await scanResult("bfc18c83127549eb8020ec0b4436330b");

      if (data.code === 200 && data.data) {
        clearInterval(interval);

        console.log("登录成功")

        const hide = message.loading('登录中...', 0);
        let token = data.data;
        if (token) {
          localStorage.setItem('token', token);
        }
        await fetchUserInfo();
        hide();
        /** 此方法会跳转到 redirect 参数所在的位置 */
        if (!history) return;
        const {query} = history.location;
        const {redirect} = query as { redirect: string };
        history.replace(redirect || '/');
      } else {
        console.log(data.msg)
      }

    }, 1000);

  };
  return (
    <div className={styles.container}>
      <div className={styles.lang} data-lang>
        {SelectLang && <SelectLang/>}
      </div>
      <div className={styles.content}>

        <Modal visible={showScanLogin} onCancel={() => {
          setShowScanLogin(false)
        }} destroyOnClose={true} maskClosable={false} title={'微信扫码登录'} footer={null}
               width={"500px"}>
          <div style={{textAlign: 'center', paddingBottom: '50px'}}>
            {
              count <= 0 ? <div onClick={loadScanData} style={{

                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  justifyContent: 'center',
                  margin: '0 auto',
                  // padding: '10px',
                }}>
                  <div style={{
                    background: '#ddd', width: '300px',
                    height: '300px',
                    margin: '5px',
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                    justifyContent: 'center',
                  }}>
                    <SyncOutlined style={{fontSize: '30px', marginBottom: '10px'}}/>
                    <div>二维码已经过期</div>
                  </div>
                </div> :
                <img src={scanQrCode} alt="扫码登录" style={{width: '300px'}} onClick={loadScanData}/>
            }
            <div>二维码有效期10分钟，点击二维码刷新</div>
            <div>请使用微信扫码</div>
            <div>扫码登录需先登录账号绑定微信（系统-账号绑定）</div>
          </div>
        </Modal>
        <LoginForm
          logo={<img alt="logo" src="/logo.svg"/>}
          title="智慧安运"
          subTitle={intl.formatMessage({id: 'pages.layouts.userLayout.title'})}
          initialValues={{
            autoLogin: true,
            username: '',
            password: '',
          }}
          actions={<div style={{textAlign: 'center'}} onClick={loadScanData}>
            <WechatOutlined key="WechatOutlined" className={styles.wechat}/> 微信扫码登录
          </div>}
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginParams);
          }}
          // actions={<div style={{textAlign: "center"}}><a>a</a></div>}
        >
          <Tabs activeKey={type} onChange={setType}>
            <Tabs.TabPane
              key="account"
              tab={intl.formatMessage({
                id: 'pages.login.accountLogin.tab',
                defaultMessage: '账户密码登录',
              })}
            />
            <Tabs.TabPane
              key="mobile"
              disabled
              tab={intl.formatMessage({
                id: 'pages.login.phoneLogin.tab',
                defaultMessage: '手机号登录',
              })}
            />
            {/*<Tabs.TabPane*/}
            {/*  key="scan"*/}
            {/*  tab={intl.formatMessage({*/}
            {/*    id: 'pages.login.scan.tab',*/}
            {/*    defaultMessage: '扫码',*/}
            {/*  })}*/}
            {/*/>*/}
          </Tabs>

          {status === 'error' && loginType === 'account' && (
            <LoginMessage content={msg ?? '用户名或者密码错误'}/>
          )}
          {type === 'account' && (
            <>
              <ProFormText
                name="username"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={styles.prefixIcon}/>,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.username.placeholder',
                  defaultMessage: '请输入用户名',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.username.required"
                        defaultMessage="请输入用户名!"
                      />
                    ),
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon}/>,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.password.placeholder',
                  defaultMessage: '请输入密码',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.password.required"
                        defaultMessage="请输入密码！"
                      />
                    ),
                  },
                ]}
              />
            </>
          )}

          {status === 'error' && loginType === 'mobile' && <LoginMessage content="验证码错误"/>}
          {type === 'mobile' && (
            <>
              <ProFormText
                fieldProps={{
                  size: 'large',
                  prefix: <MobileOutlined className={styles.prefixIcon}/>,
                }}
                name="mobile"
                placeholder={intl.formatMessage({
                  id: 'pages.login.phoneNumber.placeholder',
                  defaultMessage: '手机号',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.phoneNumber.required"
                        defaultMessage="请输入手机号！"
                      />
                    ),
                  },
                  {
                    pattern: /^1\d{10}$/,
                    message: (
                      <FormattedMessage
                        id="pages.login.phoneNumber.invalid"
                        defaultMessage="手机号格式错误！"
                      />
                    ),
                  },
                ]}
              />
              <ProFormCaptcha
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon}/>,
                }}
                captchaProps={{
                  size: 'large',
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.captcha.placeholder',
                  defaultMessage: '请输入验证码',
                })}
                captchaTextRender={(timing, count) => {
                  if (timing) {
                    return `${count} ${intl.formatMessage({
                      id: 'pages.getCaptchaSecondText',
                      defaultMessage: '获取验证码',
                    })}`;
                  }
                  return intl.formatMessage({
                    id: 'pages.login.phoneLogin.getVerificationCode',
                    defaultMessage: '获取验证码',
                  });
                }}
                name="captcha"
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.captcha.required"
                        defaultMessage="请输入验证码！"
                      />
                    ),
                  },
                ]}
                onGetCaptcha={async (phone) => {
                  const result = await getFakeCaptcha({
                    phone,
                  });
                  if (result === false) {
                    return;
                  }
                  message.success('获取验证码成功！验证码为：1234');
                }}
              />
            </>
          )}

          {type === 'scan' && (
            <>

              dsfsd
            </>
          )}
          <div
            style={{
              marginBottom: 24,
            }}
          >
            <a
              onClick={() => {
                history.push({
                  pathname: '/user/register',
                });
              }}
            >
              <FormattedMessage id="pages.login.registerAccount" defaultMessage="注册账号"/>
            </a>
            {/*<ProFormCheckbox noStyle name="autoLogin">*/}
            {/*  <FormattedMessage id="pages.login.rememberMe" defaultMessage="自动登录"/>*/}
            {/*</ProFormCheckbox>*/}
            <a
              style={{
                float: 'right',
              }}
              onClick={() => {
                history.push({
                  pathname: '/user/forget-password',
                });
              }}
            >
              <FormattedMessage id="pages.login.forgotPassword" defaultMessage="忘记密码"/>
            </a>
          </div>
        </LoginForm>
      </div>
      <Footer/>
    </div>
  );
};

export default Login;
